<template>
  <el-config-provider :locale="zhCn">
    <div class="bulk-sending">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" />
      <div class="operation-section">
        <el-button type="primary" @click="handleAddTask">新增任务</el-button>
      </div>
      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 左侧列表 -->
        <div class="table-section">
          <el-table :data="taskList" border style="width: 100%" v-loading="loading" class="custom-table">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="taskName" label="任务名称" min-width="120" show-overflow-tooltip />
            <el-table-column prop="executionTime" label="执行时间" min-width="160" show-overflow-tooltip />
            <el-table-column label="发送对象" min-width="200">
              <template #default="{ row }">
                <div class="target-info">
                  <div v-if="row.sendWxIds" class="target-group">
                    <div class="target-list">
                      好友：
                      <el-tag v-for="(name, index) in row.sendWxNames" :key="index" size="small" class="target-item">
                        {{ name }}
                      </el-tag>
                    </div>
                  </div>
                  <div v-if="row.sendGroupIds" class="target-group">
                    <div class="target-list">
                      群组：
                      <el-tag v-for="(name, index) in row.sendGroupNames" :key="index" size="small" type="success" class="target-item">
                        {{ name }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="消息类型" width="200" align="center">
              <template #default="{ row }">
                <div class="message-type-tags">
                  <el-tag v-for="(type, index) in getMessageTypes(row.messageData)" :key="index" :type="getMessageTypeTag(type)" class="message-type-tag">
                    {{ getMessageTypeText(type) }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="发送类型" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.type === '1' ? 'primary' : 'success'">
                  {{ row.type === '1' ? '立即发送' : '定时发送' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="任务状态" width="100">
              <template #default="scope">
                <el-tag
                  :style="{
                    backgroundColor: scope.row.status === '2' ? '#67c23a' : '#409eff',
                    color: '#ffffff',
                    borderColor: scope.row.status === '2' ? '#67c23a' : '#409eff'
                  }"
                >
                  {{ scope.row.status === '1' ? '执行中' : '已完成' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createByStr" label="创建人" width="120" align="center" />
            <el-table-column prop="createTime" label="创建时间" min-width="160" show-overflow-tooltip />
            <el-table-column label="操作" width="150" fixed="right" align="center">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEdit(row)">{{ row.status === '2' ? '查看' : '编辑' }}</el-button>
                <el-button type="danger" link @click="handleDelete(row)" v-if="row.status !== '2'">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 选择好友对话框 -->
      <FriendSelectDialog
        v-model="selectFriendsDialogVisible"
        :multiple="true"
        :selected-friends="editTaskForm.friends.map((f) => f.wx_id)"
        @confirm="onFriendSelectConfirm"
        @cancel="selectFriendsDialogVisible = false"
      />

      <!-- 选择群组对话框 -->
      <GroupSelectDialog
        v-model="selectGroupsDialogVisible"
        :multiple="true"
        :selected-groups="editTaskForm.groups.map((g) => g.id)"
        @confirm="onGroupSelectConfirm"
        @cancel="selectGroupsDialogVisible = false"
      />

      <!-- 编辑查看新增任务对话框 -->
      <el-dialog
        v-model="editTaskDialogVisible"
        :title="currentTask.taskId ? (currentTask.status === '2' ? '查看任务' : '编辑任务') : '新增任务'"
        width="90%"
        destroy-on-close
        class="task-dialog"
      >
        <div style="display: flex; gap: 80px; height: 83vh; overflow: hidden">
          <div style="width: 70%; height: 100%; display: flex; flex-direction: column; overflow: hidden">
            <el-form :model="editTaskForm" label-width="100px" class="task-form">
              <el-form-item label="任务名称" required>
                <el-input v-model="editTaskForm.taskName" placeholder="请输入任务名称" :disabled="currentTask.status === '2'" />
              </el-form-item>
              <el-form-item label="发送时间">
                <div class="material-section">
                  <div class="material-options">
                    <el-radio-group v-model="editTaskForm.material.sendType" :disabled="currentTask.status === '2'">
                      <el-radio label="1">立即发送</el-radio>
                      <el-radio label="2">定时发送</el-radio>
                    </el-radio-group>
                    <el-date-picker
                      v-if="editTaskForm.material.sendType === '2'"
                      v-model="editTaskForm.material.scheduleTime"
                      type="datetime"
                      placeholder="选择发送时间"
                      :disabled="currentTask.status === '2'"
                      :disabled-date="disabledBeforeToday"
                    />
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="发送对象" required class="task-dialog-send">
                <div class="target-section">
                  <div class="target-actions" v-if="currentTask.status !== '2'">
                    <el-button type="primary" @click="editTaskDialogVisible ? handleEditSelectFriends() : handleSelectFriends()">选择好友</el-button>
                    <el-button type="primary" @click="handleSelectGroups">选择群组</el-button>
                  </div>
                  <div class="target-preview" v-if="editTaskForm.friends.length || editTaskForm.groups.length">
                    <div class="target-group" v-if="editTaskForm.friends.length">
                      <div class="target-label">已选好友：</div>
                      <div class="target-list">
                        <el-tag
                          v-for="friend in editTaskForm.friends"
                          :key="friend.id"
                          :closable="currentTask.status !== '2'"
                          @close="handleRemoveFriend(friend)"
                          class="target-item"
                          :class="{ 'is-disabled': currentTask.status === '2' }"
                        >
                          {{ friend.nick_name }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="target-group" v-if="editTaskForm.groups.length">
                      <div class="target-label">已选群组：</div>
                      <div class="target-list">
                        <el-tag
                          v-for="group in editTaskForm.groups"
                          :key="group.id"
                          :closable="currentTask.status !== '2'"
                          @close="handleRemoveGroup(group)"
                          class="target-item"
                          :class="{ 'is-disabled': currentTask.status === '2' }"
                        >
                          {{ group.name }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-form>
            <div class="selectSend">
              <div class="section-title">内容类型</div>
              <el-tabs v-model="activeMessageType" class="message-tabs" :disabled="currentTask.status === '2'">
                <el-tab-pane label="文本" name="text">
                  <el-form-item label="文本内容" class="content-item">
                    <div class="content-input-wrapper">
                      <el-input
                        v-model="currentMessage.text"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入文本内容"
                        :disabled="currentTask.status === '2'"
                        maxlength="2000"
                        show-word-limit
                      />
                      <div class="emoji-trigger" @click="toggleEmojiPicker">
                        <el-icon class="emoji-icon"><ChatDotRound /></el-icon>
                      </div>
                      <div v-if="showEmojiPicker" ref="emojiPickerRef" class="emoji-picker-container" @click.stop>
                        <EmojiPicker class="emoji-picker" :i18n="zhConfig" @select="onSelectEmoji" />
                      </div>
                    </div>
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="图片" name="image">
                  <el-form-item label="图片上传">
                    <el-upload
                      class="image-uploader"
                      action="#"
                      :auto-upload="false"
                      :show-file-list="false"
                      :on-change="handleImageChange"
                      :on-remove="handleRemoveImage"
                      :on-preview="handlePreviewImage"
                      accept="image/*"
                      :disabled="currentTask.status === '2' || imageUploading"
                    >
                      <div v-if="imageUploading" class="upload-loading-wrapper">
                        <el-icon class="loading-icon is-loading" :size="30"><Loading /></el-icon>
                      </div>
                      <div v-else-if="currentMessage.imageUrl" class="preview-image-wrapper">
                        <img :src="currentMessage.imageUrl" class="preview-image" />
                        <el-icon class="remove-image-icon" @click.stop="handleRemoveImage"><Close /></el-icon>
                      </div>
                      <el-icon v-else class="upload-icon"><Plus /></el-icon>
                    </el-upload>
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="视频" name="video">
                  <el-form-item label="视频上传">
                    <el-upload
                      class="video-uploader"
                      action="#"
                      :auto-upload="false"
                      :show-file-list="false"
                      :on-change="handleVideoChange"
                      accept=".mp4"
                      :disabled="currentTask.status === '2' || videoUploading"
                    >
                      <div v-if="videoUploading" class="upload-loading-wrapper">
                        <el-icon class="loading-icon is-loading" :size="30"><Loading /></el-icon>
                      </div>
                      <div v-else-if="currentMessage.videoUrl" class="preview-video-wrapper">
                        <video :src="currentMessage.videoUrl" class="preview-video" controls />
                        <el-icon class="remove-video-icon" @click.stop="handleRemoveVideo"><Close /></el-icon>
                      </div>
                      <el-icon v-else class="upload-icon"><Plus /></el-icon>
                    </el-upload>
                  </el-form-item>
                </el-tab-pane>
                <!-- <el-tab-pane label="链接" name="link">
                  <el-form-item label="链接地址">
                    <el-input v-model="currentMessage.linkUrl" placeholder="请输入链接地址" :disabled="currentTask.status === '2'" />
                  </el-form-item>
                  <el-form-item label="链接标题">
                    <el-input v-model="currentMessage.linkTitle" placeholder="请输入链接标题" :disabled="currentTask.status === '2'" />
                  </el-form-item>
                  <el-form-item label="链接描述">
                    <el-input v-model="currentMessage.linkDesc" type="textarea" :rows="2" placeholder="请输入链接描述" :disabled="currentTask.status === '2'" maxlength="2000" show-word-limit />
                  </el-form-item>
                </el-tab-pane> -->
              </el-tabs>

              <div class="message-actions" v-if="currentTask.status !== '2'">
                <el-button type="primary" @click="handleAddMessage">添加单条</el-button>
              </div>

              <div class="message-preview-item-list">
                <div class="preview-title" v-if="messageList.length > 0">
                  已添加消息列表
                  <el-button type="primary" link @click="showMessagePreviewDialog"> </el-button>
                </div>
                <div class="message-preview-item-list">
                  <el-card v-for="(message, index) in messageList" :key="index" class="message-preview-item">
                    <div class="preview-header">
                      <div class="message-info">
                        <span class="message-type-tag" :class="message.type">{{ getMessageTypeLabel(message.type) }}</span>
                        <div class="message-content">
                          <template v-if="message.type === 'text'">
                            {{ message.text }}
                          </template>
                          <template v-else-if="message.type === 'image'">
                            <img :src="message.imageUrl" class="preview-image" />
                          </template>
                          <template v-else-if="message.type === 'video'">
                            <video :src="message.videoUrl" class="preview-video" controls />
                          </template>
                          <template v-else-if="message.type === 'link'">
                            <div class="link-preview">
                              <div class="link-title">{{ message.linkTitle }}</div>
                              <div class="link-url">{{ message.linkUrl }}</div>
                              <div class="link-desc">{{ message.linkDesc }}</div>
                            </div>
                          </template>
                        </div>
                      </div>
                      <div class="preview-actions" v-if="currentTask.status !== '2'">
                        <div class="action-buttons">
                          <el-button type="primary" link :disabled="index === 0" @click="handleMoveMessage(index, 'up')"> </el-button>
                          <el-button type="primary" link :disabled="index === messageList.length - 1" @click="handleMoveMessage(index, 'down')"> </el-button>
                          <el-button type="danger" link @click="handleDeleteMessage(index)"> </el-button>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>
          </div>
          <UserMessagePreview :messages="messageList" />
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editTaskDialogVisible = false">{{ currentTask.status === '2' ? '关闭' : '取消' }}</el-button>
            <el-button type="primary" @click="submitEditTask" v-if="currentTask.status !== '2'">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 消息预览弹窗 -->
      <ZoomInMessagePreview
        v-model="messagePreviewDialogVisible"
        :messages="messageList"
        :readonly="currentTask.status === '2'"
        @move-message="handleMoveMessage"
        @delete-message="handleDeleteMessage"
      />

      <!-- 筛选条件选择好友对话框 -->
      <FriendSelectDialog
        v-model="filterSelectFriendsDialogVisible"
        :multiple="true"
        :selected-friends="filterSelectedFriends.map((f) => f.wx_id)"
        @confirm="onFilterFriendSelectConfirm"
        @cancel="filterSelectFriendsDialogVisible = false"
      />

      <!-- 筛选条件选择群组对话框 -->
      <GroupSelectDialog
        v-model="filterSelectGroupsDialogVisible"
        :multiple="true"
        :selected-groups="filterSelectedGroups.map((g) => g.id)"
        @confirm="onFilterGroupSelectConfirm"
        @cancel="filterSelectGroupsDialogVisible = false"
      />
    </div>
  </el-config-provider>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue';
import { Plus, ArrowUp, ArrowDown, Delete, ZoomIn, ChatDotRound, Close, Loading } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { selectPrecisionMessaging, addPrecisionMessaging, deletePrecisionMessaging, uploadFile, updatePrecisionMessaging } from '@/api/userRate/bulkSending';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import FriendSelectDialog from '@/components/FriendSelect/FriendSelectDialog.vue';
import GroupSelectDialog from '@/components/GroupSelect/GroupSelectDialog.vue';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';
import FriendTagInput from '@/components/FriendSelect/FriendTagInput.vue';
import GroupTagInput from '@/components/GroupSelect/GroupTagInput.vue';
import ZoomInMessagePreview from '@/components/MessagePreview/ZoomInMessagePreview.vue';
import UserMessagePreview from '@/components/MessagePreview/UserMessagePreview.vue';
import 'vue3-emoji-picker/css';
import EmojiPicker from 'vue3-emoji-picker';

// 获取环境变量
const VITE_GLOB_APP_IMG_URL = import.meta.env.VITE_GLOB_APP_IMG_URL;

// 消息类型定义
interface MessageData {
  type: 'text' | 'image' | 'video' | 'link';
  data: string;
  text?: string;
  imageUrl?: string;
  videoUrl?: string;
  linkUrl?: string;
  linkTitle?: string;
  linkDesc?: string;
}

// 精准群发任务类型定义
interface PrecisionMessagingTask {
  taskId?: string;
  taskName: string;
  type: '1' | '2';
  sendWxIds: string;
  sendGroupIds: string;
  dateTime: string;
  executionTime?: string;
  wxId: string;
  messageData: string;
  status?: string;
  sendWxNames?: string;
  sendGroupNames?: string;
  account: string;
}

// 好友和群组类型定义
interface Friend {
  id: string;
  wx_id: string;
  nick_name: string;
  first_nick_name: string;
  avatar_url: string;
}

interface Group {
  id: string;
  name: string;
  avatar_url: string;
  memberCount: number;
  owner: string;
}

interface TaskForm {
  taskId?: string;
  taskName: string;
  material: {
    type: 'text' | 'image';
    text: string;
    sendType: '1' | '2';
    scheduleTime: string;
  };
  friends: Friend[];
  groups: Group[];
  messages: MessageData[];
  sendWxIds: string;
}

// 获取当前登录的微信ID
const currentWxId = computed(() => {
  try {
    return JSON.parse(localStorage.getItem('msgprofile') || '{}')?.wx_id || '';
  } catch (error) {
    console.error('解析msgprofile失败:', error);
    return '';
  }
});

// 筛选表单
const filterForm = reactive({
  taskName: '',
  type: '',
  status: '',
  friendIds: '',
  groupIds: ''
});

// 扩展FormItem类型
interface ExtendedFormItem extends FormItem {
  events?: {
    [key: string]: (...args: any[]) => void;
  };
}

// 表单项配置
const formItems = computed<ExtendedFormItem[]>(() => [
  {
    type: 'input',
    label: '任务名称',
    prop: 'taskName',
    placeholder: '请输入任务名称'
  },
  {
    type: 'select',
    label: '发送类型',
    prop: 'type',
    placeholder: '请选择发送类型',
    options: [
      { label: '立即发送', value: 1 },
      { label: '定时发送', value: 2 }
    ]
  },
  {
    type: 'select',
    label: '任务状态',
    prop: 'status',
    placeholder: '请选择任务状态',
    options: [
      { label: '进行中', value: 1 },
      { label: '已完成', value: 2 }
    ]
  },
  {
    type: 'custom',
    label: '发送好友',
    prop: 'friendIds',
    component: FriendTagInput,
    props: {
      placeholder: '请选择发送好友',
      selectedFriends: filterSelectedFriends.value
    },
    events: {
      click: () => handleFilterSelectFriends(),
      remove: (friend: Friend) => handleFilterRemoveFriend(friend)
    }
  },
  {
    type: 'custom',
    label: '发送群组',
    prop: 'groupIds',
    component: GroupTagInput,
    props: {
      placeholder: '请选择发送群组',
      selectedGroups: filterSelectedGroups.value
    },
    events: {
      click: () => handleFilterSelectGroups(),
      remove: (group: Group) => handleFilterRemoveGroup(group)
    }
  }
]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const loading = ref(false);

// 任务列表数据
const taskList = ref<PrecisionMessagingTask[]>([]);

// 编辑任务相关
const editTaskDialogVisible = ref(false);
const editTaskForm = reactive<TaskForm>({
  taskId: '',
  taskName: '',
  material: {
    type: 'text',
    text: '',
    sendType: '1',
    scheduleTime: ''
  },
  friends: [],
  groups: [],
  messages: [],
  sendWxIds: ''
});

// 添加currentTask的定义
const currentTask = ref<PrecisionMessagingTask>({
  taskId: '',
  taskName: '',
  type: '1',
  sendWxIds: '',
  sendGroupIds: '',
  dateTime: '',
  wxId: '',
  messageData: '[]',
  status: '1',
  account: ''
});

// 选择好友相关
const selectFriendsDialogVisible = ref(false);
const selectedFriends = ref<Friend[]>([]);

// 选择群组相关
const selectGroupsDialogVisible = ref(false);
const selectedGroups = ref<Group[]>([]);

// 筛选条件选择对话框相关
const filterSelectFriendsDialogVisible = ref(false);
const filterSelectGroupsDialogVisible = ref(false);
const filterSelectedFriends = ref<Friend[]>([]);
const filterSelectedGroups = ref<Group[]>([]);

// 消息格式选择相关
const activeMessageType = ref<MessageData['type']>('text');
const currentMessage = ref<MessageData>({
  type: 'text',
  data: '',
  text: '',
  imageUrl: '',
  videoUrl: '',
  linkUrl: '',
  linkTitle: '',
  linkDesc: ''
});
const messageList = ref<MessageData[]>([]);

// 添加消息预览弹窗相关的状态
const messagePreviewDialogVisible = ref(false);

// 表情选择器相关
const showEmojiPicker = ref(false);
const emojiPickerRef = ref<HTMLElement | null>(null);

// 表情选择器配置
const zhConfig = {
  search: '搜索',
  categories: {
    recents: '最近使用',
    smileys: '表情',
    people: '人物',
    animals: '动物',
    food: '食物',
    activities: '活动',
    travel: '旅行',
    objects: '物品',
    symbols: '符号',
    flags: '旗帜'
  },
  notFound: '没有找到表情'
};

// 切换表情选择器显示状态
const toggleEmojiPicker = (event: MouseEvent) => {
  event.stopPropagation();
  // ElMessage.info('表情选择功能正在开发中，敬请期待！');
  showEmojiPicker.value = !showEmojiPicker.value;
};

// 处理表情选择
const onSelectEmoji = (emoji: any) => {
  if (currentMessage.value.text) {
    currentMessage.value.text += emoji.i;
  } else {
    currentMessage.value.text = emoji.i;
  }
  showEmojiPicker.value = false;
};

// 点击外部关闭表情选择器
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement;
  if (emojiPickerRef.value && !emojiPickerRef.value.contains(target) && !target.closest('.emoji-trigger')) {
    showEmojiPicker.value = false;
  }
};

// 监听点击事件
onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
});

// 重置表单数据
const resetFormData = () => {
  editTaskForm.taskId = '';
  editTaskForm.taskName = '';
  editTaskForm.material = {
    type: 'text',
    text: '',
    sendType: '1',
    scheduleTime: ''
  };
  editTaskForm.friends = [];
  editTaskForm.groups = [];
  currentMessage.value = {
    type: 'text',
    data: '',
    text: '',
    imageUrl: '',
    videoUrl: '',
    linkUrl: '',
    linkTitle: '',
    linkDesc: ''
  };
  messageList.value = [];
  activeMessageType.value = 'text';
};

// 新增任务
const handleAddTask = () => {
  currentTask.value = {} as PrecisionMessagingTask;
  editTaskDialogVisible.value = true;
  resetFormData();
};

// 监听对话框关闭
onMounted(() => {
  const unwatch = watch(editTaskDialogVisible, (newVal) => {
    if (!newVal) {
      resetFormData();
      currentTask.value = {} as PrecisionMessagingTask;
    }
  });

  onBeforeUnmount(() => {
    unwatch();
  });
});
const disabledBeforeToday = (time: any) => {
  // 禁用今天及之前的日期
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
};

// 查询方法
const handleSearch = async (formData?: Record<string, any>) => {
  loading.value = true;
  console.log(formData);
  console.log(filterForm);

  try {
    // 使用传入的表单数据或当前的表单数据
    const searchData = formData || filterForm;
    const params = {
      wxId: currentWxId.value,
      taskName: searchData.taskName || undefined,
      type: searchData.type || undefined,
      status: searchData.status || undefined,
      friendIds: filterForm.friendIds || undefined,
      groupIds: filterForm.groupIds || undefined,
      current: currentPage.value,
      size: pageSize.value
    };

    // 移除所有 undefined 的参数
    Object.keys(params).forEach((key) => {
      if (params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });

    const res = await selectPrecisionMessaging(params);
    if (res.code === 200 && res.data) {
      taskList.value = res.data.records;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg || '查询失败');
    }
  } catch (error) {
    console.error('获取任务列表失败:', error);
    ElMessage.error('查询失败');
  } finally {
    loading.value = false;
  }
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.taskName = '';
  filterForm.type = '';
  filterForm.status = '';
  filterForm.friendIds = '';
  filterForm.groupIds = '';
  // 清空已选择的好友和群组
  filterSelectedFriends.value = [];
  filterSelectedGroups.value = [];
  currentPage.value = 1;
  pageSize.value = 10;
  handleSearch();
};

// 选择好友
const handleSelectFriends = () => {
  selectFriendsDialogVisible.value = true;
  selectedFriends.value = [...editTaskForm.friends];
};

// 确认选择好友
const onFriendSelectConfirm = (selected: Friend[]) => {
  // 合并新选择和之前的选择，去重
  const mergedFriends = [...editTaskForm.friends];
  selected.forEach((newFriend) => {
    if (!mergedFriends.some((existingFriend) => existingFriend.id === newFriend.id)) {
      mergedFriends.push(newFriend);
    }
  });
  editTaskForm.friends = mergedFriends;
  selectFriendsDialogVisible.value = false;
};

// 移除好友
const handleRemoveFriend = (friend: Friend) => {
  editTaskForm.friends = editTaskForm.friends.filter((f) => f.id !== friend.id);
};

// 选择群组
const handleSelectGroups = () => {
  selectGroupsDialogVisible.value = true;
  selectedGroups.value = [...editTaskForm.groups];
};

// 确认选择群组
const onGroupSelectConfirm = (groups: Group[]) => {
  // 合并新的选择和之前的选择，去重
  const mergedGroups = [...editTaskForm.groups];
  groups.forEach((newGroup) => {
    if (!mergedGroups.some((existingGroup) => existingGroup.id === newGroup.id)) {
      mergedGroups.push(newGroup);
    }
  });
  editTaskForm.groups = mergedGroups;
  selectGroupsDialogVisible.value = false;
};

// 移除群组
const handleRemoveGroup = (group: Group) => {
  editTaskForm.groups = editTaskForm.groups.filter((g) => g.id !== group.id);
};

// 删除任务
const handleDelete = async (row: PrecisionMessagingTask) => {
  if (!row.taskId) {
    ElMessage.error('任务ID不存在');
    return;
  }

  try {
    await ElMessageBox.confirm('确认删除该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await deletePrecisionMessaging(row.taskId);
    if (res.code === 200) {
      ElMessage.success('删除成功');
      handleSearch();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 处理分页变化
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  handleSearch();
};

// 监听筛选条件变化
watch([() => filterForm.taskName, () => filterForm.type, () => filterForm.status], () => {
  currentPage.value = 1;
  handleSearch();
});

// 消息相关方法
const handleAddMessage = () => {
  let isValid = true;
  let errorMessage = '';

  switch (activeMessageType.value) {
    case 'text':
      if (!currentMessage.value.text?.trim()) {
        isValid = false;
        errorMessage = '请输入文本内容';
      }
      break;
    case 'image':
      if (!currentMessage.value.imageUrl) {
        isValid = false;
        errorMessage = '请上传图片';
      }
      break;
    case 'video':
      if (!currentMessage.value.videoUrl) {
        isValid = false;
        errorMessage = '请上传视频';
      }
      break;
    case 'link':
      if (!currentMessage.value.linkUrl?.trim()) {
        isValid = false;
        errorMessage = '请输入链接地址';
      }
      break;
  }

  if (!isValid) {
    ElMessage.warning(errorMessage);
    return;
  }

  const { type, data, ...rest } = currentMessage.value;
  const newMessage: MessageData = {
    type: activeMessageType.value,
    data: JSON.stringify(
      Object.fromEntries(
        Object.entries(rest)
          .filter(([_, value]) => value !== '' && value !== undefined && value !== null)
          .map(([key, value]) => {
            switch (activeMessageType.value) {
              case 'text':
                return ['content', value];
              case 'image':
                return ['url', value];
              case 'video':
                return ['url', value];
              case 'link':
                return ['url', value];
              default:
                return [key, value];
            }
          })
      )
    ),
    ...rest
  };

  messageList.value.push(newMessage);
  currentMessage.value = {
    type: 'text',
    data: '',
    text: '',
    imageUrl: '',
    videoUrl: '',
    linkUrl: '',
    linkTitle: '',
    linkDesc: ''
  };
};

const imageUploading = ref(false);
const videoUploading = ref(false);

const handleImageChange = async (event: { raw: File }) => {
  if (activeMessageType.value !== 'image') {
    ElMessage.warning('请先选择"图片"类型再上传图片');
    return;
  }
  const file = event.raw;
  if (file) {
    if (!file.type.startsWith('image/')) {
      ElMessage.error('只支持图片格式的文件');
      return;
    }

    // 检查文件大小限制（100MB = 100 * 1024 * 1024 bytes）
    const maxSize = 100 * 1024 * 1024; // 100MB
    if (file.size > maxSize) {
      ElMessage.error(`文件大小不能超过100MB，当前文件大小：${(file.size / 1024 / 1024).toFixed(2)}MB`);
      return;
    }

    imageUploading.value = true;
    try {
      const response = await uploadFile(file);
      if (response.data) {
        currentMessage.value.imageUrl = VITE_GLOB_APP_IMG_URL + response.data;
        ElMessage.success('图片上传成功');
      }
    } catch (error) {
      console.error('图片上传失败:', error);
      ElMessage.error('图片上传失败');
    } finally {
      imageUploading.value = false;
    }
  }
};

const handleVideoChange = async (event: { raw: File }) => {
  if (activeMessageType.value !== 'video') {
    ElMessage.warning('请先选择"视频"类型再上传视频');
    return;
  }
  const file = event.raw;
  if (file) {
    if (!file.type.includes('mp4') && !file.name.toLowerCase().endsWith('.mp4')) {
      ElMessage.error('只支持MP4格式的视频文件');
      return;
    }

    // 检查文件大小限制（100MB = 100 * 1024 * 1024 bytes）
    const maxSize = 100 * 1024 * 1024; // 100MB
    if (file.size > maxSize) {
      ElMessage.error(`文件大小不能超过100MB，当前文件大小：${(file.size / 1024 / 1024).toFixed(2)}MB`);
      return;
    }

    videoUploading.value = true;
    try {
      const response = await uploadFile(file);
      if (response.data) {
        currentMessage.value.videoUrl = VITE_GLOB_APP_IMG_URL + response.data;
        ElMessage.success('视频上传成功');
      }
    } catch (error) {
      console.error('视频上传失败:', error);
      ElMessage.error('视频上传失败');
    } finally {
      videoUploading.value = false;
    }
  }
};

const handleDeleteMessage = (index: number) => {
  messageList.value.splice(index, 1);
};

const getMessageTypeLabel = (type: MessageData['type']) => {
  const typeMap: Record<MessageData['type'], string> = {
    text: '文本',
    image: '图片',
    video: '视频',
    link: '链接'
  };
  return typeMap[type];
};

const handleMoveMessage = (index: number, direction: 'up' | 'down') => {
  const newIndex = direction === 'up' ? index - 1 : index + 1;
  if (newIndex < 0 || newIndex >= messageList.value.length) return;

  const temp = messageList.value[index];
  messageList.value[index] = messageList.value[newIndex];
  messageList.value[newIndex] = temp;
};

// 消息容器引用
const messageContainer = ref<HTMLElement | null>(null);

// 监听消息列表变化，自动滚动到底部
watch(
  messageList,
  () => {
    nextTick(() => {
      if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
      }
    });
  },
  { deep: true }
);

const handleRemoveImage = () => {
  currentMessage.value.imageUrl = '';
};

const handlePreviewImage = () => {
  if (currentMessage.value.imageUrl) {
    window.open(currentMessage.value.imageUrl, '_blank');
  }
};

// 编辑任务
const handleEdit = (row: PrecisionMessagingTask) => {
  currentTask.value = row;
  editTaskDialogVisible.value = true;
  editTaskForm.taskId = row.taskId || '';
  editTaskForm.taskName = row.taskName;
  editTaskForm.material.sendType = row.type;
  editTaskForm.material.scheduleTime = row.executionTime || '';

  // 直接使用行数据中的好友信息，不调用接口
  if (row.sendWxIds) {
    const friendIds = row.sendWxIds.split(',');
    const friendNames = row.sendWxNames || [];
    editTaskForm.friends = friendIds.map((wxId, index) => ({
      id: wxId,
      wx_id: wxId,
      nick_name: friendNames[index] || wxId,
      first_nick_name: friendNames[index] || wxId,
      avatar_url: ''
    }));
  } else {
    editTaskForm.friends = [];
  }

  // 直接使用行数据中的群组信息，不调用接口
  if (row.sendGroupIds) {
    const groupIds = row.sendGroupIds.split(',');
    const groupNames = row.sendGroupNames || [];
    editTaskForm.groups = groupIds.map((groupId, index) => ({
      id: groupId,
      name: groupNames[index] || groupId,
      avatar_url: '',
      memberCount: 0,
      owner: ''
    }));
  } else {
    editTaskForm.groups = [];
  }

  try {
    const messageDataList = JSON.parse(row.messageData || '[]');
    messageList.value = messageDataList.map((msg: any) => {
      let messageData = msg.data;
      if (msg.type === 'link') {
        try {
          messageData = JSON.parse(msg.data);
        } catch (e) {
          console.error('解析消息数据失败:', e);
          messageData = {};
        }
      }

      const baseMessage = {
        type: msg.type,
        data: msg.data
      };

      switch (msg.type) {
        case 'text':
          return {
            ...baseMessage,
            text: messageData
          };
        case 'image':
          return {
            ...baseMessage,
            imageUrl: messageData
          };
        case 'video':
          return {
            ...baseMessage,
            videoUrl: messageData
          };
        case 'link':
          return {
            ...baseMessage,
            linkUrl: messageData.url || '',
            linkTitle: messageData.title || '',
            linkDesc: messageData.desc || ''
          };
        default:
          return baseMessage;
      }
    });

    if (messageList.value.length > 0) {
      activeMessageType.value = messageList.value[0].type;
    }
  } catch (error) {
    console.error('解析消息数据失败:', error);
    messageList.value = [];
  }
};

// 提交编辑
const submitEditTask = async () => {
  if (!editTaskForm.taskName) {
    ElMessage.warning('请输入任务名称');
    return;
  }

  if (editTaskForm.friends.length === 0 && editTaskForm.groups.length === 0) {
    ElMessage.warning('请选择发送对象');
    return;
  }

  if (messageList.value.length === 0) {
    ElMessage.warning('请新增消息内容');
    return;
  }

  // 如果是定时发送，验证日期时间是否已填写
  if (editTaskForm.material.sendType === '2' && !editTaskForm.material.scheduleTime) {
    ElMessage.warning('请选择定时发送时间');
    return;
  }

  const messageDataStr = JSON.stringify(
    messageList.value.map((msg) => {
      let data = '';
      switch (msg.type) {
        case 'text':
          data = msg.text || '';
          break;
        case 'image':
          data = msg.imageUrl || '';
          break;
        case 'video':
          data = msg.videoUrl || '';
          break;
        case 'link':
          data = JSON.stringify({
            url: msg.linkUrl,
            title: msg.linkTitle,
            desc: msg.linkDesc
          });
          break;
      }
      return {
        type: msg.type,
        data: data
      };
    })
  );

  // 处理日期时间格式
  let formattedDateTime = '';
  if (editTaskForm.material.scheduleTime) {
    const date = new Date(editTaskForm.material.scheduleTime);
    formattedDateTime = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(
      date.getHours()
    ).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
  }

  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  const account = userInfo.username || '';

  const taskData: PrecisionMessagingTask = {
    taskId: editTaskForm.taskId,
    taskName: editTaskForm.taskName,
    type: editTaskForm.material.sendType as '1' | '2',
    sendWxIds: editTaskForm.friends.map((f) => f.wx_id).join(','),
    sendGroupIds: editTaskForm.groups.map((g) => g.id).join(','),
    dateTime: formattedDateTime,
    wxId: currentWxId.value,
    messageData: messageDataStr,
    account
  };

  try {
    if (editTaskForm.taskId) {
      const res = await updatePrecisionMessaging(taskData as any);
      if (res.code === 200) {
        ElMessage.success('更新成功');
        editTaskDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error(res.msg || '更新失败');
      }
    } else {
      const res = await addPrecisionMessaging(taskData as any);
      if (res.code === 200) {
        ElMessage.success('新增成功');
        editTaskDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error(res.msg || '新增失败');
      }
    }
  } catch (error) {
    console.error('提交任务失败:', error);
    ElMessage.error('操作失败');
  }
};

// 添加消息类型相关的方法
const getMessageTypeTag = (type: string) => {
  switch (type) {
    case 'text':
      return 'info';
    case 'image':
      return 'warning';
    case 'video':
      return 'danger';
    default:
      return 'default';
  }
};

const getMessageTypeText = (type: string) => {
  switch (type) {
    case 'text':
      return '文本';
    case 'image':
      return '图片';
    case 'video':
      return '视频';
    default:
      return '其他';
  }
};

// 获取消息类型列表
const getMessageTypes = (messageData: string) => {
  try {
    const messages = JSON.parse(messageData || '[]');
    return [...new Set(messages.map((msg: any) => msg.type))];
  } catch (error) {
    return [];
  }
};

// 初始化加载数据
onMounted(() => {
  handleSearch();
});

const handleEditSelectFriends = () => {
  handleSelectFriends();
};

// 显示消息预览弹窗
const showMessagePreviewDialog = () => {
  messagePreviewDialogVisible.value = true;
};

// 筛选条件相关的方法
const handleFilterSelectFriends = () => {
  filterSelectFriendsDialogVisible.value = true;
  filterSelectedFriends.value = [...filterSelectedFriends.value];
};

const handleFilterSelectGroups = () => {
  filterSelectGroupsDialogVisible.value = true;
  filterSelectedGroups.value = [...filterSelectedGroups.value];
};

const handleFilterRemoveFriend = (friend: Friend) => {
  filterSelectedFriends.value = filterSelectedFriends.value.filter((f) => f.id !== friend.id);
  filterForm.friendIds = filterSelectedFriends.value.map((f) => f.wx_id).join(',');
};

const handleFilterRemoveGroup = (group: Group) => {
  filterSelectedGroups.value = filterSelectedGroups.value.filter((g) => g.id !== group.id);
  filterForm.groupIds = filterSelectedGroups.value.map((g) => g.id).join(',');
};

const onFilterFriendSelectConfirm = (selected: Friend[]) => {
  // 合并新的选择和之前的选择，去重
  const mergedFriends = [...filterSelectedFriends.value];
  selected.forEach((newFriend) => {
    if (!mergedFriends.some((existingFriend) => existingFriend.id === newFriend.id)) {
      mergedFriends.push(newFriend);
    }
  });
  filterSelectedFriends.value = mergedFriends;
  filterForm.friendIds = mergedFriends.map((f) => f.wx_id).join(',');
  filterSelectFriendsDialogVisible.value = false;
};

const onFilterGroupSelectConfirm = (groups: Group[]) => {
  // 合并新的选择和之前的选择，去重
  const mergedGroups = [...filterSelectedGroups.value];
  groups.forEach((newGroup) => {
    if (!mergedGroups.some((existingGroup) => existingGroup.id === newGroup.id)) {
      mergedGroups.push(newGroup);
    }
  });
  filterSelectedGroups.value = mergedGroups;
  filterForm.groupIds = mergedGroups.map((g) => g.id).join(',');
  filterSelectGroupsDialogVisible.value = false;
};

const handleRemoveVideo = () => {
  currentMessage.value.videoUrl = '';
};
</script>

<style lang="scss" scoped>
@use './bulkSending.scss';
@use './sendmsgdialog.scss';
.remove-image-icon {
  position: absolute;
  top: 2px;
  right: 2px;
  cursor: pointer;
  color: #f56c6c;
  background: #fff;
  border-radius: 50%;
  font-size: 18px;
  z-index: 2;
}
.remove-video-icon {
  position: absolute;
  top: 2px;
  right: 2px;
  cursor: pointer;
  color: #f56c6c;
  background: #fff;
  border-radius: 50%;
  font-size: 18px;
  z-index: 2;
}
.upload-loading-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
}
.loading-icon {
  font-size: 30px;
  color: #409eff;
}
</style>
